/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.lidovky.articles.updates;

import cz.mzk.rehan.commons.DatastreamId;
import cz.mzk.kramerius.fedoraaccess.FedoraConnector;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public class ArticleUpdater {

    private static final Logger logger = Logger.getLogger(ArticleUpdater.class.getName());
    private final FedoraConnector con;
    private Map<String, DatastreamUpdater> updaterMap = new HashMap<String, DatastreamUpdater>();

    public ArticleUpdater(FedoraConnector con) {
        this.con = con;
    }

    public boolean updateDatastream(String articlePid, DatastreamId dsId, String dsUpdaterClassName) {
        try {
            DatastreamUpdater dsUpdater = getDcUpdater(dsUpdaterClassName);
            Document original = loadDatastreamContent(articlePid, dsId);
            Document updated = dsUpdater.update(original);
            return con.updateDatastreamInlineContent(articlePid, dsId, updated);
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
            return false;
        }
    }

    private DatastreamUpdater getDcUpdater(String className) throws Exception {
        DatastreamUpdater updater = updaterMap.get(className);
        if (updater == null) {
            updater = loadDcUpdater(className);
            updaterMap.put(className, updater);
        }
        return updater;
    }

    private DatastreamUpdater loadDcUpdater(String className) throws Exception {
        Class updaterClass = Class.forName(className);
        return (DatastreamUpdater) updaterClass.newInstance();
    }

    private Document loadDatastreamContent(String articlePid, DatastreamId dsId) {
        return con.getDatastreamDissemination(articlePid, dsId);
    }
}
